const db = uniCloud.database();
const uniID = require('uni-id-common');

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context });
  let body = event;
  
  // 如果 body 是字符串，进行解析
  if (event.body != undefined) {
    body = JSON.parse(event.body);
  }

  try {
    // 校验token，获取uid
    const { uid } = await uniIDIns.checkToken(body.uniIdToken);
    
    // 如果没有uid，身份验证失败
    if (!uid) {
      return { code: 403, msg: "身份验证失败" };
    }
    
    // 获取传入的hasSubscribed值
    const { hasSubscribed } = body;
    
    // 查找所有与该uid相关的预约记录
    const appointmentRecords = await db.collection("appoint_schedule")
      .where({ uid })  // 查找与uid相关的记录
      .get();

    // 如果有记录
    if (appointmentRecords.data.length > 0) {
      // 遍历每一条记录，更新或创建hasSubscribed字段
      const updatePromises = appointmentRecords.data.map(record => {
        // 如果没有hasSubscribed字段，则创建并初始化
        if (!record.hasSubscribed) {
          return db.collection("appoint_schedule")
            .doc(record._id)
            .update({
              hasSubscribed: hasSubscribed  // 初始化或更新字段
            });
        } else {
          // 如果已存在hasSubscribed字段，直接更新
          return db.collection("appoint_schedule")
            .doc(record._id)
            .update({
              hasSubscribed: hasSubscribed  // 更新字段
            });
        }
      });

      // 等待所有更新操作完成
      await Promise.all(updatePromises);

      return {
        code: 0,
        msg: "订阅状态更新成功",
        data: {
          hasSubscribed
        }
      };
    } else {
      // 如果没有找到相关预约记录
      return {
        code: 1,
        msg: "未找到相关预约记录",
      };
    }
  } catch (error) {
    console.error("更新订阅状态失败:", error);
    return {
      code: -6,
      msg: "数据库查询或更新失败"
    };
  }
};
